<template>
    <div id="addCard" class="desclass">
        <!-- <head-tip title='新增名帖' :isback=true>
        </head-tip> -->
        <header class="header">
            <router-link v-if="returnpath==''" to='/mine?type=3' class="addTrend">
                <i class="el-icon-arrow-left"></i>
            </router-link>
            <a @click="returnFrom" v-else class="addTrend"><i class="el-icon-arrow-left"></i></a>
            新增名帖
        </header>
        <form id="form-card-add" name="form-card-add">
            <div class="croppa">
                <croppa 
                @image-remove="imgRemove"
                @new-image-drawn="getDefaultBlob"
                v-model="myCroppa"
                :width="80"
                :height="80"
                :placeholder="'上传头像'"
                :canvas-color="'#ffffff'"
                :placeholder-font-size="14" id="picCroppa" class="myCroppa">
                    <img crossOrigin="anonymous" :src="defaultUrl" slot="initial">
                </croppa>
                <div class="bnt-list">
                    <el-button :type="logotype" @click="setlogo" size="mini" v-if="urlpic">{{mess}}</el-button>
                    <!-- <el-button type="info" @click="rotatepic" size="mini" v-if="urlpic">旋转</el-button> -->
                    <el-button type="success" @click="uploadCroppedImageC" size="mini" v-if="urlpic">确认裁剪</el-button>
                    <input type="hidden" id="cplogo" name="cplogo" v-model="formtext.personlogo">
                </div>
            </div>
            <div class="backpic">
                <input @change="uploadCroppedImageB" name="companylogo" id="cclogo" type="file" accpet="image/*"/>
                <img v-if="srcurl" :src="srcurl" style="width:80%;">
                <p>上传背景图</p>
            </div>
            <div class="myInfo-main baseinfo">
                <p class="info-one type" @click="changeCardtype">
                    <span class="redinput"></span><span class="left-bq">名帖类型</span>
                    <label class="center-info" id="itype">{{formtext.typeval}}</label>
                    <i class="iconfont icon-you"></i>
                </p>
                <p class="info-one userid">
                    <span class="redinput"></span><span class="left-bq">帖主</span>
                    <label class="center-info" id="userid">{{username}}</label>
                </p>
                <p v-if="formtext.typevalint!==''" class="info-one userName">
                    <span class="redinput"></span>
                    <span v-if="formtext.typevalint==1" class="left-bq">姓名</span>
                    <span class="left-bq" v-else>公司简称</span>
                    <label class="center-info"><input name="cname" id="cname" type="text"  value="" placeholder="必填" v-model="formtext.cname"/></label>
                </p>
                <div class="myInfo-main companyinfo" v-if="companyshow">
                    <p class="info-one">
                        <span class="left-bq">公司名称</span>
                        <label class="center-info"><input v-model="formtext.ccompany" name="ccompany" placeholder="必填" id="ccompany" type="text"  value=""/></label>
                    </p>
                    
                </div> 
                <div v-if="formtext.typevalint!==''">
                    <p class="info-one" v-for="(item,index) in telArr" :key="index">
                        <span class="redinput"></span><span class="left-bq">联系电话</span>
                        <label  style="width:60%;" class="center-info"><input name="clogtel" id="clogtel" type="text"  value="" placeholder="必填" v-model="item['tel']"/></label>
                        <i @click="delInput(item)" style="line-height:3rem;margin-right:0.5rem;" class="el-icon-remove-outline"></i>
                        <i @click="addInput" style="line-height:3rem;" class="el-icon-circle-plus-outline"></i>
                    </p>
                </div>
               
            </div>

            <div class="myInfo-main personalinfo" v-if="!companyshow">
              
            </div>
            
        </form> 
        <transition name="cardtypename">
            <div class="cardtype" v-show="cardtype">
                <div class="cardtypechild">
                    <p v-for="(item,index) in typearr" :key="index" class="hasbottom" @click="checkType(item.typeval,item.typevalint)">{{item.typeval}}</p>
                    <p @click="changeCardtype">取消</p>
                </div>
            </div>
        </transition>
        <!-- 底部 -->
        <div id="foot">
            <a @click="tosave" href="javascript:void(0)" class="edit-card-button add-card-submit">保存</a>
        </div>
    </div>
</template>

<script>
import headTip from '@/components/common/head'
import remoteLoad from '../../../js/remoteLoad.js'
import {addCard} from '../../../js/dataServe.js'
import { VueEditor } from 'vue2-editor'
export default {
    data(){
        let self = this;
        return {
            returnpath:sessionStorage.returnpath,
            returnval:true,
            telArr:[{tel:''}],
            defaultUrl:'/static/h4.jpg',
            username:decodeURIComponent(sessionStorage.username),
            myCroppa:{},
            myCroppas:{},
            mess:'设置为二维码logo',
            logotype:'info',
            bntbg:false,
            bntpic:false,
            cardtype:false,
            typearr:[{
                'typeval':'个人',
                'typevalint':1
            },{
                'typeval':'公司',
                'typevalint':0
            }],
            companyshow:false,
            formtext:{
                cemail:"",
                bcodeflag:false,
                personlogo:"",
                companylogo:"",
                cname:"",
                itype:"",
                cdesc:"",
                clogtel:"",
                caddress:"",
                cprovince:"",
                ccity:"",
                cdistrict:"",
                ilatitude:"",
                ilongitude:"",
                ctags:"",
                iindustryid:"",
                typeval:'请单击选择',
                typevalint:'',
                ccompany:"",
                cdepartment:"",
                cpost:"",
                ccurl:"",
                cwx:""
            },
            srcurl:"",
            customToolbar: [
                [{ 'size': ['small', false, 'large'] }],
                ['bold', 'italic', 'underline'],
                [{ 'align': [] }]
            ]
        }   
    },
    components:{
        VueEditor,
        headTip
        // quillEditor
    },
    async created () {
        let self = this;
        if (window.AMap){
            this.initMap();
        }else{
            await remoteLoad(`http://webapi.amap.com/maps?v=1.4.2&key=b02674c30e6ee45bdfb3c21d9c0b9c69`);
            // console.log(window.AMap)
            this.initMap();
        }
    },
    methods: {
        returnFrom(){
            this.$router.push({path:this.returnpath})
            sessionStorage.returnpath = ''
        },
        addInput(){
            if(this.telArr.length<5){
                this.telArr.push({tel:''})
            }else{
                alert('最多填5个')
            }
        },
        delInput(item){
            if(this.telArr.length>1){
                let index = this.telArr.indexOf(item);
                if (index > -1) {
                    this.telArr.splice(index, 1);
                }
            }else{
                alert('请至少填一个');
            }
        },
        initMap () {
            let mapObj = new AMap.Map('');
            mapObj.plugin('AMap.Geolocation', function () {
                let geolocation = new AMap.Geolocation({
                    enableHighAccuracy: true,//是否使用高精度定位，默认:true
                    timeout: 10000,          //超过10秒后停止定位，默认：无穷大
                    maximumAge: 10,           //定位结果缓存0毫秒，默认：0
                    convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
                    showButton: true,        //显示定位按钮，默认：true
                    buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
                    buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                    showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
                    showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
                    panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
                    zoomToAccuracy:true      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                });
                mapObj.addControl(geolocation);
                geolocation.getCityInfo(function(stutas,result){
                    sessionStorage.setItem('cityname',result.city)
                    sessionStorage.setItem('citycode',result.citycode)
                });
            });

        },
        getDefaultBlob(){
            let self = this
            let urlc = self.myCroppa.generateBlob( blob => {
                    self.formtext.personlogo = blob
                },
                'image/jpeg',
                0.8)
            // console.log(self.formtext.personlogo)
        },
        uploadCroppedImageC() {
            let self = this
            let urlc = self.myCroppa.generateBlob( blob => {
                self.formtext.personlogo = blob
            },
            'image/jpeg',
            0.8)
            // console.log(self.formtext.personlogo)
            self.$message({
                            duration: 2000,
                            message: '裁剪成功',
                            type: 'success'
                        })
        },
        uploadCroppedImageB(event) {

            let file = event.target.files[0];
            this.formtext.companylogo = file;

            let self = this;
            let reader = new FileReader();

            reader.onloadend = function () {
                // 图片的 base64 格式, 可以直接当成 img 的 src 属性值
                let dataURL = reader.result;
                self.srcurl = dataURL
                // console.log(dataURL)
            };
            reader.readAsDataURL(file); // 读出 base64
            // console.log(this.srcurl)
        },
        rotatepic(){
            this.myCroppa.rotate({step:1});
        },
        rotatebg(){
            this.myCroppas.rotate({step:1});
        },
        searchPageIsShow(){
            this.$router.push({path:"/mine/searchPosition",query:{type:3}})
        },
        positionShow(){
            this.$router.push({path:"/mine/position",query:{type:3}})
        },
        tipsShow(){
            this.$router.push({path:"/mine/tips",query:{type:3}})
        },
        industryShow(){
            this.$router.push({path:"/mine/industry",query:{type:3}})
        },
        changeCardtype(){
            this.cardtype = !this.cardtype
        },
        checkType(typeval,typevalint){
            if(typeval === '公司'){
                this.companyshow = true
            }else{
                this.companyshow = false
            }
            this.formtext.typeval = typeval;
            this.formtext.typevalint = typevalint;
            this.cardtype = !this.cardtype;
            this.$store.commit('changeItype',{val:typevalint});
        },
        //是否设为二维码logo
        setlogo(){
            if(!this.formtext.bcodeflag){
                this.formtext.bcodeflag = true
                this.logotype = 'success'
                this.mess = "点击取消logo设置"
            }else{
                this.formtext.bcodeflag = false
                this.logotype = 'info'
                this.mess = "设置为二维码logo"
            }
            
        },
        imgRemove(){
            this.formtext.personlogo = ""
        },
        //保持
        tosave(){
            // console.log(1112)
            this.formtext.caddress = this.$store.state.address;
            this.formtext.cprovince = this.$store.state.province;
            this.formtext.ccity = this.$store.state.city;
            this.formtext.cdistrict = this.$store.state.town;
            this.formtext.ilatitude = this.$store.state.lat?this.$store.state.lat:'';
            this.formtext.ilongitude = this.$store.state.lng?this.$store.state.lng:'';
            this.formtext.ctags = this.$store.state.tipid?this.$store.state.tipid:'';
            this.formtext.ctechtags = this.$store.state.tip;
            this.formtext.iindustryid = this.$store.state.industryid?this.$store.state.industryid:'';
            this.formtext.itype = this.$store.state.itype;
            let formtext = this.formtext;
            let self = this;
            if(self.formtext.typevalint === ''){
                alert('请选择名帖类型先!')
                return false;
            }
            if(self.companyshow){
                if(!self.formtext.ccompany.length){
                    alert('公司类型名帖公司名称不能为空！')
                    return false;
                }
            }
            
            if(!self.formtext.cname.length){
                alert('姓名（或公司简称）不能为空！')
                return false;
            }
            self.formtext.clogtel = ''
            this.telArr.forEach((v,k)=>{
                self.formtext.clogtel += v.tel+','
                if(!v.tel.length){
                    alert('第'+(k+1)+'个电话不能为空！')
                    this.returnval = false
                }else if(!new RegExp("^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$").test(v.tel) && !new RegExp("^(0[0-9]{2,3}\-)([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$").test(v.tel)){
                    alert('第'+(k+1)+'个请输入正确的手机号或座机号！') 
                    this.returnval = false
                }else{
                    this.returnval = true
                }
            })
            if(!this.returnval){
                return false
            }
            if(self.formtext.cemail!=''){
                let rEmail = !new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$").test(self.formtext.cemail)
                if(rEmail){
                    alert('请输入正确的邮箱')
                    return false;
                }
            }
            
            
            let formdata = new FormData();

            Object.keys(formtext).forEach(key => {
                            formdata.append(key,formtext[key])
                        })
            //加载条
            const loading = this.$loading({
                                            lock: true,
                                            text: 'Loading',
                                            spinner: 'el-icon-loading',
                                            background: 'rgba(0, 0, 0, 0.7)',
                                            text:'拼命提交中'
                                        });
            let responseData = addCard(formdata);
            responseData.then((res)=>{
                                        if(res.result == 1){
                                            loading.close();
                                            self.$message({
                                                duration: 2000,
                                                message: '添加成功',
                                                type: 'success'
                                            })
                                            setTimeout( () => {
                                                if(this.formtext.itype == 1){
                                                    if(this.$store.state.cards.length>0){
                                                        this.$store.commit('addCards',{pval:res.data,cval:''});
                                                    }
                                                    self.$router.push({path:"/mine/myCard",query:{type:3}})
                                                }else{
                                                    if(this.$store.state.cards.length>0){
                                                        this.$store.commit('addCards',{pval:'',cval:res.data});
                                                    }
                                                    self.$router.push({path:"/mine/myCard",query:{type:3}})
                                                }
                                                if(sessionStorage.returnpath){
                                                    sessionStorage.returnpath = ''
                                                }
                                                this.$store.commit('changeAllCards',{val:[]});
                                            },0)
                                        }else{
                                            loading.close();
                                            self.$message({
                                                duration: 2000,
                                                message: res.msg,
                                                type: 'error'
                                            })
                                        }
                                    })
        }
    },
    beforeRouteLeave(to, from, next) {
        // console.log(to)
        if(to.path == '/mine/myCompany' || to.path == '/mine/myCard'){
            to.meta.keepAlive = false;
        }
        next();
    },
    computed:{
        urlpic:function(){
            if(this.myCroppa.generateDataUrl){
                return Boolean(this.myCroppa.generateDataUrl())
            }
        },
        urlbg:function(){
            if(this.myCroppas.generateDataUrl){
                return Boolean(this.myCroppas.generateDataUrl())
            }
        }
    },
    beforeRouteEnter(to,from,next){
        if(from.name == 'mine'){
            to.meta.isActive = true;
        }else{
            if(from.name!=null){
                sessionStorage.setItem('returnpath',from.fullPath)
            }   
        }
        next();
    },
    beforeRouteLeave(to,from,next){
        from.meta.isActive = false;
        next();
    }
}
</script>

<style scoped >
.iconfont{
    position:absolute;
    top:0;
    right:0.5rem;
}
#addCard {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    background: #ffffff;
}
#addCard .info-one{
    height:3rem;
    line-height:3rem;
}
.desclass{
    min-height:100%;
}
.header{
    width:100%;
    height:3rem;
    line-height:3rem;
    background:#eee;
    color:#333;
    font-size:1.2rem;
    position: fixed;
    top: 0;
    z-index:5;
}
.header i{ color: #333;}
.change-bg{
    height: 3rem;
    line-height: 3rem;
    display: flex;
    position: relative;
    justify-content: space-between;
    padding: 0 1rem;
    box-sizing: border-box;
    background:#ffffff;
    margin:2rem 0 ;
}
.change-bg input{
    opacity: 0;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}
#form-card-add{
    padding: 3rem 0 4rem 0;
}
.info-one{
    width: 100%;
    height: 3rem;
    display: flex;
    padding: 0 2%;
    position:relative;
    box-sizing: border-box;
    background: #ffffff;
    border-bottom: 1px solid #EBEEF5;
}
.info-one label{
    text-align:left;
}
.info-one .left-bq{
    width:30%;
    text-align:left;
}
.redinput{
    position: absolute;
    left: 0.5rem;
}
.center-info{
    width: 70%;
}
.center-info input{
    width: 100%;
    height: 2.8rem;
    line-height:2.8rem;
    border: 0;
    border: none;
    box-sizing: border-box;
    outline: none;
    display:block;
}
.myCroppa{
    background:#ffffff;
    margin-top:23px;
}
.croppa{
    width:100%;
    border-bottom: 1px solid #EBEEF5;
    box-sizing:border-box;
    background:#ffffff;
}
#searchText {
    width: 100%;
    height: 2.5rem;
    border: 1px solid #e4e4e4;
    padding-left:1rem;
    box-sizing:border-box;
    font-size:1rem;
}
.searchPosition{
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    z-index: 100;
    background: #ffffff;
}
#head{
    background:#2790A6;
    font-size:1.2rem;
    color:#ffffff;
}
.parentSearch{
    margin-top:1rem;
    padding:0 1rem;
}
.info-one{
    position:relative;
}
#chooseaddress{
    width:100%;
    height:100%;
    position:absolute;
    top:0;
    opacity:0;
}
.address{
    text-align:left;
}
.cardtype{
    position:fixed;
    top:0;
    left:0;
    bottom:0;
    right:0;
    margin:auto;
    width:100%;
    height:100%;
    background:rgba(0,0,0,0.5)
}
.cardtypechild{
    position:absolute;
    top:0;
    left:0;
    bottom:0;
    right:0;
    margin:auto;
    width:50%;
    height:9rem;
    background: #ffffff;
    border-radius: 1rem;
}
.cardtypechild p{
    box-sizing:border-box;
    height:3rem;
    line-height:3rem;
}
.hasbottom{
    border-bottom:1px solid #EBEEF5;
}
#foot {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    background: #333333;
    height:3rem;
    width:100%;
    position: fixed;
    bottom: 0;
    box-sizing: border-box;
    z-index: 2000;
}
.edit-card-button{
    display: block;
    width: 100%;
    height: 3rem;
    background: #00AA76;
    text-align: center;
    font-size: 1.3rem;
    color: #fff;
    line-height: 3rem;
    position: fixed;
    bottom: 0px;
    z-index: 9999999;
}
.backpic{
    position:relative;
    background:#ffffff;
    border-bottom:1px solid #EBEEF5;
    box-sizing:border-bottom;
}
.backpic input{
    position: absolute;
    left:0;width:100%;
    height:100%; 
    opacity: 0;
}
.backpic p{
    font-size:1rem;
    height: 3rem;
    line-height:3rem;
}
header a{
    position: absolute;
    left: 1rem;
    color: #ffffff;
    width: 2rem;
}
.quill-editor-example{
    margin-top:1rem;
    background: #ffffff;
    text-align:left;
}
.quill-editor{
    height:20rem;
}
</style>
